import type { Polygon } from 'geojson'
import { keyGen } from '@/common'
import { geometryOfCircle, type LngLat } from '@/geom/great-circle'
import { meter2MetricStr } from '@/widgets'
import { symbolProperties, type MapFeatures } from '@/map'
import { addAuxGraphic, auxGraphicStyle, type AuxGraphic } from '../core'
import { auxGraphicProperties } from '../core/base'

export interface AuxCircle extends AuxGraphic {
  type: 'Circle'
  center: LngLat
  radius: number
}

const nameGen = keyGen('辅助圆#')

function nextName(): string {
  return nameGen.next()
}

export function addAuxCircle(center: LngLat, radius: number) {
  addAuxGraphic<AuxCircle>({
    type: 'Circle',
    name: nextName(),
    center,
    radius
  })
}

export function toPolygon(ac: AuxCircle): Polygon {
  return geometryOfCircle(ac.center, ac.radius)
}

export function toFeature(ac: AuxCircle, g: Polygon[]): MapFeatures {
  const pl = g.length > 0 ? g[0] : toPolygon(ac)
  const center = ac.center
  const centerCoord = [center.lng, center.lat]
  return {
    symbol: [
      {
        type: 'Feature',
        geometry: {
          type: 'Point',
          coordinates: centerCoord
        },
        properties: symbolProperties(
          ` ${ac.name}\n${meter2MetricStr(ac.radius)}`,
          auxGraphicStyle.symbol
        )
      }
    ],
    line: [
      {
        type: 'Feature',
        geometry: {
          type: 'LineString',
          coordinates: [centerCoord, pl.coordinates[0][5]]
        },
        properties: auxGraphicProperties.line
      },
      {
        type: 'Feature',
        geometry: pl,
        properties: auxGraphicProperties.line
      }
    ]
  }
}
